<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@taglib prefix="mvc" uri="http://www.springframework.org/tags/form" %>
<%@taglib prefix="fmt" uri="http://www.springframework.org/tags" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>公文交换设置</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=10,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
    <link rel="stylesheet" type="text/css" href="/lib/layui/layui/css/layui.css"/>
    <script type="text/javascript" src="/lib/layui/layui/layui.js"></script>
    <script type="text/javascript" src="/lib/layui/layui/layui.all.js"></script>
    <script type="text/javascript" src="/js/news/jquery-1.9.1.js"></script>
    <script type="text/javascript" src="/lib/jquery-2.1.4.min.js"></script>
    <script src="/js/base/base.js" type="text/javascript" charset="utf-8"></script>

    <style>
        .layui-anim-upbit {
            max-height: 200px !important;
        }
        .layui-form-label {
            width: 100px !important;
        }
        .layui-input-block {
            margin-left: 130px !important;
        }
        .textarea {
            float: left;
            cursor: pointer;
            resize:none;
            min-height: 38px;
            width: 350px;
        }
        .add {
            display: inline-block;
            padding: 2px 15px;
            font-weight: 400;
            line-height: 20px;
            text-align: center;
        }
        .table_box .layui-form-checkbox span{
            margin-left: 20px;
        }
    </style>
</head>
<body>
    <div class="layui-tab layui-tab-brief" lay-filter="docDemoTabBrief">
        <ul class="layui-tab-title">
            <li class="layui-this">系统内公文交换设置</li>
<%--            <li>外部系统公文交换</li>--%>
            <li>外部收文单位管理</li>
        </ul>
        <div class="layui-tab-content">
            <!-- 系统内公文交换设置 -->
            <div class="layui-tab-item layui-show">
                <div class="layui-form" >
                    <div style="display: flex">
                        <div class="layui-form-item" style="width: 30%;">
                            <label class="layui-form-label">筛选</label>
                            <div class="layui-input-block">
                                <select name="city" lay-verify="required" class="search" lay-filter="searchSelect">
                                    <option value="">全部单位类型</option>
                                </select>
                            </div>
                        </div>
                        <div style="margin-left: 30%;"> <button type="button" class="layui-btn btn_new">添加</button></div>
                    </div>
                    <div class="table_box"><table id="internalTable" lay-filter="internalTable"></table></div>
                </div>
            </div>
            <!-- 外部系统公文交换 -->
<%--            <div class="layui-tab-item">--%>
<%--                <div class="layui-tab-item layui-show">--%>
<%--                    <div class="layui-form" >--%>
<%--                        <div style="display: flex">--%>
<%--                            <div class="layui-form-item" style="width: 30%;">--%>
<%--                                <label class="layui-form-label">筛选</label>--%>
<%--                                <div class="layui-input-block">--%>
<%--                                    <select name="city" lay-verify="required" class="searchs" lay-filter="searchSelects">--%>
<%--                                        <option value="">全部单位类型</option>--%>
<%--                                    </select>--%>
<%--                                </div>--%>
<%--                            </div>--%>
<%--                            <div style="margin-left: 30%;"> <button type="button" class="layui-btn btn_news">添加</button></div>--%>
<%--                        </div>--%>
<%--                        <div class="table_box"><table id="internalTables" lay-filter="internalTables"></table></div>--%>
<%--                    </div>--%>
<%--                </div>--%>
<%--            </div>--%>
            <!-- 外部收文单位管理 -->
            <div class="layui-tab-item">
                <div class="layui-tab-item layui-show">
                    <div class="layui-form" >
                        <div style="display: flex">
                            <div class="layui-form-item" style="width: 30%;">
                                <label class="layui-form-label">筛选</label>
                                <div class="layui-input-block">
                                    <select name="city" lay-verify="required" class="search_outer" lay-filter="searchSelectOuter">
                                        <option value="">全部单位类型</option>
                                    </select>
                                </div>
                            </div>
                            <div style="margin-left: 30%;"> <button type="button" class="layui-btn add_btn">添加</button></div>
                        </div>
                        <div class="table_box"><table id="outerUnitTables" lay-filter="outerUnitTables"></table></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script type="text/html" id="internalBar">
        <a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>

    <script type="text/html" id="externalBar">
        <a class="layui-btn layui-btn-xs" lay-event="edits">修改</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="dels">删除</a>
    </script>

    <script type="text/html" id="outerUnitBar">
        <a class="layui-btn layui-btn-xs" lay-event="1">修改</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="2">删除</a>
    </script>

    <!-- 新增、修改-内部公文交换设置-弹窗 -->
    <div type="text/html" id="newModal" style="display: none;padding: 10px 40px 10px 0;">
        <form class="layui-form" lay-filter="newForm" id="addform">
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="margin-right: 5px; color: red;">*</span>单位类型</label>
                <div class="layui-input-block">
                    <select name="unitType" class="unit_type" lay-filter="aihao">

                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="margin-right: 5px; color: red;">*</span>发文单位名</label>
                <div class="layui-input-block">
                    <input type="text" name="fromUnit" placeholder="发文单位名" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="margin-right: 5px; color: red;">*</span>收文单位名</label>
                <div class="layui-input-block">
                    <input type="text" name="receiveUnit" placeholder="收文单位名" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="margin-right: 5px; color: red;">*</span>部门名称</label>
                <div class="layui-input-block">
                    <textarea name="exchangeDeptId" id="SendCompany" required lay-verify="required" placeholder="请选择部门" class="layui-textarea textarea" disabled></textarea>
                    <a href="javascript:;" id="exchangeDeptId" class="add" style="color: blue;"><fmt:message code="global.lang.add" /></a>
                    <a href="javascript:;" id="clearSendCompany" class="add" style="color: red;">清空</a>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="margin-right: 5px; color: red;">*</span>部门对应用户</label>
                <div class="layui-input-block">
                    <textarea name="exchangeUserId" id="Senduser" style="min-height: 80px" required lay-verify="required" placeholder="请选择对应部门用户" class="layui-textarea textarea exchange_user" disabled></textarea>
                    <a href="javascript:;" id="exchangeUserId" class="add" style="color: blue;"><fmt:message code="global.lang.add" /></a>
                    <a href="javascript:;" id="clearSenduser" class="add" style="color: red;">清空</a>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">上级单位</label>
                <div class="layui-input-block">
                    <textarea name="parentDept" id="parentDept" required lay-verify="required" placeholder="请选择上级单位" class="layui-textarea textarea" disabled></textarea>
                    <a href="javascript:;" id="addParentDept" class="add" style="color: blue;"><fmt:message code="global.lang.add" /></a>
                    <a href="javascript:;" id="clearParentDept" class="add" style="color: red;">清空</a>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">下级单位</label>
                <div class="layui-input-block">
                    <textarea name="childDepts" id="childDepts" required lay-verify="required" placeholder="请选择下级单位" class="layui-textarea textarea" disabled></textarea>
                    <a href="javascript:;" id="addChildDepts" class="add" style="color: blue;"><fmt:message code="global.lang.add" /></a>
                    <a href="javascript:;" id="clearChildDepts" class="add" style="color: red;">清空</a>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">权限</label>
                <div class="layui-input-block">
                    <input type="checkbox" name="documentPriv" class="documentPriv" value="1" title="收文" lay-skin="primary">
                    <input type="checkbox" name="documentPriv" class="documentPriv" value="2" title="发文" lay-skin="primary">
                </div>
            </div>
        </form>
    </div>
    <!-- 新增、修改-外部公文交换设置-弹窗 -->
    <div type="text/html" id="newModals" style="display: none;padding: 10px 40px 10px 0;">
        <form class="layui-form" lay-filter="newForm" id="addforms">
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="margin-right: 5px; color: red;">*</span>单位类型</label>
                <div class="layui-input-block">
                    <select name="unitType" class="unit_types" lay-filter="aihao">

                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="margin-right: 5px; color: red;">*</span>发文单位名</label>
                <div class="layui-input-block">
                    <input type="text" id="fromUnit" name="fromUnit" placeholder="发文单位名" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="margin-right: 5px; color: red;">*</span>收文单位名</label>
                <div class="layui-input-block">
                    <input type="text" id="receiveUnit" name="receiveUnit" placeholder="收文单位名" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="margin-right: 5px; color: red;">*</span>部门名称</label>
                <div class="layui-input-block">
                    <textarea name="exchangeDeptId" id="SendCompanys" required lay-verify="required" placeholder="请选择部门" class="layui-textarea textarea" disabled></textarea>
                    <a href="javascript:;" id="exchangeDeptIds" class="add" style="color: blue;"><fmt:message code="global.lang.add" /></a>
                    <a href="javascript:;" id="clearSendCompanys" class="add" style="color: red;">清空</a>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="margin-right: 5px; color: red;">*</span>部门对应用户</label>
                <div class="layui-input-block">
                    <textarea name="exchangeUserId" id="Sendusers" style="min-height: 80px" required lay-verify="required" placeholder="请选择对应部门用户" class="layui-textarea textarea exchange_user" disabled></textarea>
                    <a href="javascript:;" id="exchangeUserIds" class="add" style="color: blue;"><fmt:message code="global.lang.add" /></a>
                    <a href="javascript:;" id="clearSendusers" class="add" style="color: red;">清空</a>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">上级单位</label>
                <div class="layui-input-block">
                    <textarea name="parentDept" id="parentDepts" required lay-verify="required" placeholder="请选择上级单位" class="layui-textarea textarea" disabled></textarea>
                    <a href="javascript:;" id="addParentDepts" class="add" style="color: blue;"><fmt:message code="global.lang.add" /></a>
                    <a href="javascript:;" id="clearParentDepts" class="add" style="color: red;">清空</a>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">下级单位</label>
                <div class="layui-input-block">
                    <textarea name="childDepts" id="childDeptss" required lay-verify="required" placeholder="请选择下级单位" class="layui-textarea textarea" disabled></textarea>
                    <a href="javascript:;" id="addChildDeptss" class="add" style="color: blue;"><fmt:message code="global.lang.add" /></a>
                    <a href="javascript:;" id="clearChildDeptss" class="add" style="color: red;">清空</a>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">权限</label>
                <div class="layui-input-block">
                    <input type="checkbox" name="documentPriv" class="documentPrivs" value="1" title="收文" lay-skin="primary">
                    <input type="checkbox" name="documentPriv" class="documentPrivs" value="2" title="发文" lay-skin="primary">
                </div>
            </div>
        </form>
    </div>
    <!-- 新增、修改-外部收文单位管理-弹窗 -->
    <div type="text/html" id="newOuterUnitModal" style="display: none;padding: 10px 40px 10px 0;">
        <form class="layui-form" lay-filter="newouterunitform" id="newouterunitform">
            <div class="layui-form-item">
                <label class="layui-form-label">排序号</label>
                <div class="layui-input-block">
                    <input type="text" name="ouNo" placeholder="请输入排序号" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="margin-right: 5px; color: red;">*</span>外部单位类别</label>
                <div class="layui-input-block">
                    <select name="ouType" class="ou_type" lay-filter="ouType">

                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="margin-right: 5px; color: red;">*</span>单位全称</label>
                <div class="layui-input-block">
                    <input type="text" name="ounitFullName" placeholder="请输入单位全称" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="margin-right: 5px; color: red;">*</span>单位简称</label>
                <div class="layui-input-block">
                    <input type="text" name="ounitShotName" placeholder="请输入单位简称" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="margin-right: 5px; color: red;">*</span>接收单位名称</label>
                <div class="layui-input-block">
                    <input type="text" name="ounitName" placeholder="请输入接收单位名称" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="margin-right: 5px; color: red;">*</span>接收单位部门</label>
                <div class="layui-input-block">
                    <input type="text" name="deptName" placeholder="请输入接收单位部门" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="margin-right: 5px; color: red;">*</span>来文类型</label>
                <div class="layui-input-block">
                    <select name="docType" class="doc_type" lay-filter="docType">
                        <option value="1">上级来文</option>
                        <option value="2">下级来文</option>
                        <option value="3">其他来文</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="margin-right: 5px; color: red;">*</span>主送/抄送</label>
                <div class="layui-input-block">
                    <input type="radio" name="deliveryType" class="delivery_type" value="1" title="主送" lay-skin="primary">
                    <input type="radio" name="deliveryType" class="delivery_type" value="2" title="抄送" lay-skin="primary">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="margin-right: 5px; color: red;">*</span>说明</label>
                <div class="layui-input-block">
                    <textarea name="ounitDesc" placeholder="外部单位说明" rows="3" class="layui-textarea" style="resize: none;"></textarea>
                </div>
            </div>
        </form>
    </div>
    <script>
        var dept_id='SendCompany';
        var user_id='Senduser';

        loadALLDeptSidebarurl = '/getOrgList';

        layui.use(['form','table', 'layer'], function(){
            var form = layui.form;
            var table = layui.table;
            var layer = layui.layer;

            form.render();

            // 初始化-内部公文交换设置-表格
            var internalTable = table.render({
                elem: '#internalTable'
                ,url: '/documentExchangeSet/selectDocumentExchange?exchangeType=0&time='+ new Date().getTime() //数据接口
                ,page: true //开启分页
                ,cols: [[ //表头
                    {field: 'unitTypeName', align:'center',title: '单位类型', minWidth: 110},
                    {field: 'fromUnit', align:'center',title: '发文单位名', minWidth: 110},
                    {field: 'receiveUnit', align:'center',title: '收文单位名', minWidth: 160},
                    {field: 'exchangeDeptName', align:'center',title: '部门名称',minWidth: 150},
                    {field: 'exchangeUserName',align:'center', title: '部门对应用户',minWidth: 160},
                    {field: 'parentDeptName', align:'center',title: '上级单位',minWidth: 150},
                    {field: 'childDeptsName',align:'center', title: '下级单位',minWidth: 170},
                    {
                        field: 'documentPriv',align:'center', title: '权限', width: '12%', minWidth: '147px',
                        templet: function(d) {
                            var html = '';
                            var str = '<input type="checkbox" title="收文" disabled lay-skin="primary">';
                            var str2 = '<input type="checkbox" title="发文" disabled lay-skin="primary">';
                            if (d.documentPriv && d.documentPriv.length > 0) {
                                var documentPrivs = d.documentPriv.split(',');

                                if (documentPrivs.length > 0) {
                                    documentPrivs.forEach(function(item){
                                        if (item == 1) {
                                            str = '<input type="checkbox" title="收文" lay-skin="primary" disabled checked>';
                                        } else if (item == 2) {
                                            str2 = '<input type="checkbox" title="发文" lay-skin="primary" disabled checked>';
                                        }
                                    })
                                }
                            }
                            html = str + str2;
                            return html;
                        },
                    },
                    {field: 'createUserName',align:'center', title: '创建人',  minWidth: 110},
                    {
                        field: 'createTime',align:'center', title: '创建时间', minWidth: 160,
                        templet: function (d) {
                            return formatDate(d.createTime);
                        }
                    },
                    {fixed: 'right', title: '操作',align:'center', toolbar: '#internalBar',minWidth: 130}
                ]]
                ,response: {
                    statusName: 'flag',  //规定数据状态的字段名称，默认：code
                    statusCode: true,   //规定成功的状态码，默认：0
                    dataName: 'obj',    //规定数据列表的字段名称，默认：data
                    countName: 'totleNum'
                }
            });

            //监听-内部公文交换设置-表格-工具条
            table.on('tool(internalTable)', function(obj){
                var tData = obj.data;
                var layEvent = obj.event;

                if(layEvent === 'edit'){
                    var exchangeDeptId = tData.exchangeDeptId ? tData.exchangeDeptId+',' : '';
                    $('#SendCompany').get(0).setAttribute('deptid', exchangeDeptId);
                    $('#SendCompany').val(tData.exchangeDeptName);
                    $('#Senduser').get(0).setAttribute('user_id', tData.exchangeUserId);
                    $('#Senduser').val(tData.exchangeUserName);
                    var parentDept = tData.parentDept ? tData.parentDept+',' : '';
                    $('#parentDept').get(0).setAttribute('deptid', parentDept);
                    $('#parentDept').val(tData.parentDeptName);
                    $('#childDepts').get(0).setAttribute('deptid', tData.childDepts);
                    $('#childDepts').val(tData.childDeptsName);
                    if (tData.documentPriv && tData.documentPriv.length > 0) {
                        var documentPrivs = tData.documentPriv.split(',');
                        if (documentPrivs.length > 0) {
                            var checks = $('.documentPriv');
                            documentPrivs.forEach(function(item){
                                if (item == 1) {
                                    checks[0].checked = true;
                                } else if (item == 2) {
                                    checks[1].checked = true;
                                }
                            })
                        }
                    }
                    form.val("newForm", {
                        'unitType': tData.unitType,
                        "fromUnit": tData.fromUnit,
                        'receiveUnit': tData.receiveUnit
                    });

                    layer.open({
                        type: 1,
                        title: '设置收发文单位',
                        content: $('#newModal'),
                        area: ['600px', '500px'],
                        btn: ['确认', '取消'],
                        yes: function(){
                            var data = {exchangeId: tData.exchangeId, exchangeType: tData.exchangeType};
                            var t = $('#addform [name]').serializeArray();
                            $.each(t, function() {
                                data[this.name] = this.value;
                            });

                            data['exchangeDeptId'] = $('#SendCompany').get(0).getAttribute('deptid');
                            data['exchangeUserId'] = $('#Senduser').get(0).getAttribute('user_id');
                            data['parentDept'] = $('#parentDept').get(0).getAttribute('deptid') || '';
                            data['childDepts'] = $('#childDepts').get(0).getAttribute('deptid') || '';

                            if (data['fromUnit'].trim() == '' || data['fromUnit'].trim().length == 0) {
                                layer.msg('请输入发文单位名');
                                return false;
                            }

                            if (data['receiveUnit'].trim() == '' || data['receiveUnit'].trim().length == 0) {
                                layer.msg('请输入收文单位名');
                                return false;
                            }

                            if (data['exchangeDeptId'].length == 0) {
                                layer.msg('请选择部门名称');
                                return false;
                            }

                            if (data['exchangeUserId'].length == 0) {
                                layer.msg('请选择部门对应用户');
                                return false;
                            }

                            var checks = $('.documentPriv:checkbox:checked');
                            var documentPriv = '';
                            if (checks.length > 0) {
                                checks.each(function(){
                                    documentPriv += $(this).val() + ',';
                                });
                            }

                            data['exchangeDeptId'] = parseInt(data['exchangeDeptId'].split(',')[0]);
                            data['parentDept'] = data['parentDept'] == '' ? '' : parseInt(data['parentDept'].split(',')[0]);
                            data['documentPriv'] = documentPriv;
                            $.post('/documentExchangeSet/updateDocumentExchange', data, function(res){
                                if (res.flag) {
                                    resetForm(form)
                                    layer.closeAll();
                                    internalTable.reload({
                                        url: '/documentExchangeSet/selectDocumentExchange?exchangeType=0&time='+ new Date().getTime()
                                        ,page: {
                                            curr: 1
                                        }
                                    });
                                }
                            });
                        },
                        btn2: function(){
                            resetForm(form)
                        },
                        cancel: function(){
                            resetForm(form)
                        }
                    })
                } else if(layEvent === 'del'){ //删除
                    layer.confirm('真的删除行么', function(index){
                        obj.del();
                        layer.close(index);
                        $.post('/documentExchangeSet/deleteDocumentExchange', {exchangeId: tData.exchangeId}, function(res){
                            if (res.flag) {
                                internalTable.reload({
                                    url: '/documentExchangeSet/selectDocumentExchange?exchangeType=0&time='+ new Date().getTime()
                                    ,page: {
                                        curr: 1
                                    }
                                });
                            }
                        })
                    });
                }
            });

            $.get('/documentExchangeSet/selectByType?SysCode=DOC_EXCHANGE_UNIT_TYPE', function(res){
                if (res.flag && res.obj.length > 0) {
                    res.obj.forEach(function(item){
                        var opt = '<option value="'+item.codeNo+'">'+item.codeName+'</option>';
                        $('.unit_type').append($(opt));
                        $('.search').append($(opt));
                        $('.unit_types').append($(opt));
                        $('.searchs').append($(opt));
                    });
                    form.render();
                }
            });

            $.get('/documentExchangeSet/selectByType?SysCode=DOCUMENT_EXCHANGE_OUTUNIT', function(res){
                if (res.flag && res.obj.length > 0) {
                    res.obj.forEach(function(item){
                        var opt = '<option value="'+item.codeNo+'">'+item.codeName+'</option>';
                        $('.ou_type').append($(opt));
                        $('.search_outer').append($(opt));
                    });
                    form.render();
                }
            });

            // 筛选-内部公文交换设置
            form.on('select(searchSelect)', function(data){
                internalTable.reload({
                    where: {
                        unitType: data.value
                    }
                    ,page: {
                        curr: 1
                    }
                });
            });

            // 选择部门
            $('#exchangeDeptId').on('click', function(){
                dept_id='SendCompany';
                $.popWindow("../common/selectDept?0");
            });
            $('#clearSendCompany').on("click", function(){
                $('#SendCompany').get(0).setAttribute('deptid', '');
                $('#SendCompany').val('');
            });

            // 选择部门对应用户
            $("#exchangeUserId").on("click",function(){//选人员控件
                user_id='Senduser';
                $.ajax({
                    url:'/imfriends/getIsFriends',
                    type:'get',
                    dataType:'json',
                    data:{},
                    success:function(obj){
                        if(obj.object == 1){
                            $.popWindow("../common/selectUserIMAddGroup");
                        }else{
                            $.popWindow("../common/selectUser");
                        }
                    },
                    error:function(res){
                        $.popWindow("../common/selectUser");
                    }
                })
            });
            $('#clearSenduser').on("click", function(){
                $('#Senduser').get(0).setAttribute('user_id', '');
                $('#Senduser').val('');
            });

            // 选择上级单位
            $('#addParentDept').on('click', function(){
                dept_id='parentDept';
                $.popWindow("../common/selectDept?0");
            });
            $('#clearParentDept').on('click', function(){
                $('#parentDept').get(0).setAttribute('deptid', '');
                $('#parentDept').val('');
            });

            // 选择下级单位
            $('#addChildDepts').on('click', function(){
                dept_id='childDepts';
                $.popWindow("../common/selectDept");
            });
            $('#clearChildDepts').on('click', function(){
                $('#childDepts').get(0).setAttribute('deptid', '');
                $('#childDepts').val('');
            });

            // 新增-内部公文交换设置
            $('.btn_new').on('click', function(){
                layer.open({
                    type: 1,
                    title: '设置收发文单位',
                    content: $('#newModal'),
                    area: ['600px', '500px'],
                    btn: ['确认', '取消'],
                    yes: function(){
                        var data = {exchangeType: '0'};
                        var t = $('#addform [name]').serializeArray();
                        $.each(t, function() {
                            data[this.name] = this.value;
                        });
                        data['exchangeDeptId'] = $('#SendCompany').get(0).getAttribute('deptid');
                        data['exchangeUserId'] = $('#Senduser').get(0).getAttribute('user_id');
                        data['parentDept'] = $('#parentDept').get(0).getAttribute('deptid') || '';
                        data['childDepts'] = $('#childDepts').get(0).getAttribute('deptid') || '';

                        if (data['fromUnit'].trim() == '' || data['fromUnit'].trim().length == 0) {
                            layer.msg('请输入发文单位名');
                            return false;
                        }

                        if (data['receiveUnit'].trim() == '' || data['receiveUnit'].trim().length == 0) {
                            layer.msg('请输入收文单位名');
                            return false;
                        }

                        if (data['exchangeDeptId'] == null ) {
                            layer.msg('请选择部门名称');
                            return false;
                        }

                        if (data['exchangeUserId'] == null ) {
                            layer.msg('请选择部门对应用户');
                            return false;
                        }

                        var checks = $('.documentPriv:checkbox:checked');
                        var documentPriv = '';
                        if (checks.length > 0) {
                            checks.each(function(){
                                documentPriv += $(this).val() + ',';
                            });
                        }

                        data['exchangeDeptId'] = parseInt(data['exchangeDeptId'].split(',')[0]);
                        data['parentDept'] = data['parentDept'] == '' ? '' : parseInt(data['parentDept'].split(',')[0]);
                        data['documentPriv'] = documentPriv;
                        $.post('/documentExchangeSet/insertDocumentExchange', data, function(res){
                           if (res.flag) {
                               resetForm(form);
                               $('#newModal').hide();
                               layer.closeAll();
                               internalTable.reload({
                                   url: '/documentExchangeSet/selectDocumentExchange?exchangeType=0&time='+ new Date().getTime()
                                   ,page: {
                                       curr: 1
                                   }
                               });
                           }
                        });
                    },
                    btn2: function(){
                        resetForm(form)
                    },
                    cancel: function(){
                        resetForm(form)
                    }
                })
            });


            // 新增-外部公文数据
            var internalTables = table.render({
                elem: '#internalTables'
                , url: '/documentExchangeSet/selectDocumentExchange?exchangeType=1&time=' + new Date().getTime() //数据接口
                , page: true //开启分页
                , cols: [[ //表头
                    {field: 'unitTypeName', align: 'center', title: '单位类型', minWidth: 110},
                    {field: 'fromUnit', align: 'center', title: '发文单位名', minWidth: 110},
                    {field: 'receiveUnit', align: 'center', title: '收文单位名', minWidth: 160},
                    {field: 'exchangeDeptName', align: 'center', title: '部门名称', minWidth: 150},
                    {field: 'exchangeUserName', align: 'center', title: '部门对应用户', minWidth: 160},
                    {field: 'parentDeptName', align: 'center', title: '上级单位', minWidth: 150},
                    {field: 'childDeptsName', align: 'center', title: '下级单位', minWidth: 170},
                    {
                        field: 'documentPriv', align: 'center', title: '权限', width: '12%', minWidth: '147px',
                        templet: function (d) {
                            var html = '';
                            var str = '<input type="checkbox" title="收文" disabled lay-skin="primary">';
                            var str2 = '<input type="checkbox" title="发文" disabled lay-skin="primary">';
                            if (d.documentPriv && d.documentPriv.length > 0) {
                                var documentPrivs = d.documentPriv.split(',');

                                if (documentPrivs.length > 0) {
                                    documentPrivs.forEach(function (item) {
                                        if (item == 1) {
                                            str = '<input type="checkbox" title="收文" lay-skin="primary" disabled checked>';
                                        } else if (item == 2) {
                                            str2 = '<input type="checkbox" title="发文" lay-skin="primary" disabled checked>';
                                        }
                                    })
                                }
                            }
                            html = str + str2;
                            return html;
                        },
                    },
                    {field: 'createUserName', align: 'center', title: '创建人', minWidth: 110},
                    {
                        field: 'createTime', align: 'center', title: '创建时间', minWidth: 160,
                        templet: function (d) {
                            return formatDate(d.createTime);
                        }
                    },
                    {fixed: 'right', title: '操作', align: 'center', toolbar: '#externalBar', minWidth: 130}
                ]]
                , response: {
                    statusName: 'flag',  //规定数据状态的字段名称，默认：code
                    statusCode: true,   //规定成功的状态码，默认：0
                    dataName: 'obj',    //规定数据列表的字段名称，默认：data
                    countName: 'totleNum'
                }
            });

            //监听-外部公文交换设置-表格-工具条
            table.on('tool(internalTables)', function(obj){
                var tData = obj.data;
                var layEvent = obj.event;

                if(layEvent === 'edits'){
                    var exchangeDeptId = tData.exchangeDeptId ? tData.exchangeDeptId+',' : '';
                    $('#SendCompanys').get(0).setAttribute('deptid', exchangeDeptId);
                    $('#SendCompanys').val(tData.exchangeDeptName);
                    $('#Sendusers').get(0).setAttribute('user_id', tData.exchangeUserId);
                    $('#Sendusers').val(tData.exchangeUserName);
                    var parentDept = tData.parentDept ? tData.parentDept+',' : '';
                    $('#parentDepts').get(0).setAttribute('deptid', parentDept);
                    $('#parentDepts').val(tData.parentDeptName);
                    $('#childDeptss').get(0).setAttribute('deptid', tData.childDepts);
                    $('#childDeptss').val(tData.childDeptsName);
                    if (tData.documentPriv && tData.documentPriv.length > 0) {
                        var documentPrivs = tData.documentPriv.split(',');
                        if (documentPrivs.length > 0) {
                            var checks = $('.documentPrivs');
                            documentPrivs.forEach(function(item){
                                if (item == 1) {
                                    checks[0].checked = true;
                                } else if (item == 2) {
                                    checks[1].checked = true;
                                }
                            })
                        }
                    }
                    form.val("newForm", {
                        'unitType': tData.unitType,
                        "fromUnit": tData.fromUnit,
                        'receiveUnit': tData.receiveUnit
                    });

                    layer.open({
                        type: 1,
                        title: '设置收发文单位',
                        content: $('#newModals'),
                        area: ['600px', '500px'],
                        btn: ['确认', '取消'],
                        yes: function(){
                            var data = {exchangeId: tData.exchangeId, exchangeType: tData.exchangeType};
                            var t = $('#addforms [name]').serializeArray();
                            $.each(t, function() {
                                data[this.name] = this.value;
                            });

                            data['exchangeDeptId'] = $('#SendCompanys').get(0).getAttribute('deptid');
                            data['exchangeUserId'] = $('#Sendusers').get(0).getAttribute('user_id');
                            data['parentDept'] = $('#parentDepts').get(0).getAttribute('deptid') || '';
                            data['childDepts'] = $('#childDeptss').get(0).getAttribute('deptid') || '';

                            if (data['fromUnit']=='') {
                                layer.msg('请输入发文单位名');
                                return false;
                            }

                            if (data['receiveUnit']=='') {
                                layer.msg('请输入收文单位名');
                                return false;
                            }

                            if (data['exchangeDeptId']== null) {
                                layer.msg('请选择部门名称');
                                return false;
                            }

                            if (data['exchangeUserId']== null) {
                                layer.msg('请选择部门对应用户');
                                return false;
                            }

                            var checks = $('.documentPriv:checkbox:checked');
                            var documentPriv = '';
                            if (checks.length > 0) {
                                checks.each(function(){
                                    documentPriv += $(this).val() + ',';
                                });
                            }

                            data['exchangeDeptId'] = parseInt(data['exchangeDeptId'].split(',')[0]);
                            data['parentDept'] = data['parentDept'] == '' ? '' : parseInt(data['parentDept'].split(',')[0]);
                            data['documentPriv'] = documentPriv;
                            $.post('/documentExchangeSet/updateDocumentExchange', data, function(res){
                                if (res.flag) {
                                    resetForm(form)
                                    layer.closeAll();
                                    internalTables.reload({
                                        url: '/documentExchangeSet/selectDocumentExchange?exchangeType=1&time='+ new Date().getTime()
                                        ,page: {
                                            curr: 1
                                        }
                                    });
                                }
                            });
                        },
                        btn2: function(){
                            resetForm(form)
                        },
                        cancel: function(){
                            resetForm(form)
                        }
                    })
                } else if(layEvent === 'dels'){ //删除
                    layer.confirm('真的删除行么', function(index){
                        obj.del();
                        layer.close(index);
                        $.post('/documentExchangeSet/deleteDocumentExchange', {exchangeId: tData.exchangeId}, function(res){
                            if (res.flag) {
                                internalTable.reload({
                                    url: '/documentExchangeSet/selectDocumentExchange?exchangeType=1&time='+ new Date().getTime()
                                    ,page: {
                                        curr: 1
                                    }
                                });
                            }
                        })
                    });
                }
            });

            // 筛选-外部公文交换设置
            form.on('select(searchSelects)', function(data){
                internalTables.reload({
                    where: {
                        unitType: data.value
                    }
                    ,page: {
                        curr: 1
                    }
                });
            });

            // 选择部门
            $('#exchangeDeptIds').on('click', function(){
                dept_id='SendCompanys';
                $.popWindow("../common/selectDept?0");
            });
            $('#clearSendCompanys').on("click", function(){
                $('#SendCompanys').get(0).setAttribute('deptid', '');
                $('#SendCompanys').val('');
            });

            // 选择部门对应用户
            $("#exchangeUserIds").on("click",function(){//选人员控件
                user_id='Sendusers';
                $.ajax({
                    url:'/imfriends/getIsFriends',
                    type:'get',
                    dataType:'json',
                    data:{},
                    success:function(obj){
                        if(obj.object == 1){
                            $.popWindow("../common/selectUserIMAddGroup");
                        }else{
                            $.popWindow("../common/selectUser");
                        }
                    },
                    error:function(res){
                        $.popWindow("../common/selectUser");
                    }
                })
            });
            $('#clearSendusers').on("click", function(){
                $('#Sendusers').get(0).setAttribute('user_id', '');
                $('#Sendusers').val('');
            });

            // 选择上级单位
            $('#addParentDepts').on('click', function(){
                dept_id='parentDepts';
                $.popWindow("../common/selectDept?0");
            });
            $('#clearParentDepts').on('click', function(){
                $('#parentDepts').get(0).setAttribute('deptid', '');
                $('#parentDepts').val('');
            });

            // 选择下级单位
            $('#addChildDeptss').on('click', function(){
                dept_id='childDeptss';
                $.popWindow("../common/selectDept");
            });
            $('#clearChildDeptss').on('click', function(){
                $('#childDeptss').get(0).setAttribute('deptid', '');
                $('#childDeptss').val('');
            });

            // 新增-外部公文交换设置
            $('.btn_news').on('click', function(){
                layer.open({
                    type: 1,
                    title: '设置收发文单位',
                    content: $('#newModals'),
                    area: ['600px', '500px'],
                    btn: ['确认', '取消'],
                    yes: function(){
                        var data = {exchangeType: '1'};
                        var t = $('#addforms [name]').serializeArray();
                        $.each(t, function() {
                            data[this.name] = this.value;
                        });
                        data['exchangeDeptId'] = $('#SendCompanys').get(0).getAttribute('deptid');
                        data['exchangeUserId'] = $('#Sendusers').get(0).getAttribute('user_id');
                        data['parentDept'] = $('#parentDepts').get(0).getAttribute('deptid') || '';
                        data['childDepts'] = $('#childDeptss').get(0).getAttribute('deptid') || '';

                        if (data['fromUnit'] == '' ) {
                            layer.msg('请输入发文单位名');
                            return false;
                        }

                        if (data['receiveUnit']=='' ) {
                            layer.msg('请输入收文单位名');
                            return false;
                        }

                        if (data['exchangeDeptId'] == null ) {
                            layer.msg('请选择部门名称');
                            return false;
                        }

                        if (data['exchangeUserId'] == null ) {
                            layer.msg('请选择部门对应用户');
                            return false;
                        }

                        var checks = $('.documentPriv:checkbox:checked');
                        var documentPriv = '';
                        if (checks.length > 0) {
                            checks.each(function(){
                                documentPriv += $(this).val() + ',';
                            });
                        }

                        data['exchangeDeptId'] = parseInt(data['exchangeDeptId'].split(',')[0]);
                        data['parentDept'] = data['parentDept'] == '' ? '' : parseInt(data['parentDept'].split(',')[0]);
                        data['documentPriv'] = documentPriv;
                        $.post('/documentExchangeSet/insertDocumentExchange', data, function(res){
                            if (res.flag) {
                                resetForm(form);
                                $('#newModal').hide();
                                layer.closeAll();
                                internalTables.reload({
                                    url: '/documentExchangeSet/selectDocumentExchange?exchangeType=1&time='+ new Date().getTime()
                                    ,page: {
                                        curr: 1
                                    }
                                });
                            }
                        });
                    },
                    btn2: function(){
                        resetForm(form)
                    },
                    cancel: function(){
                        resetForm(form)
                    }
                })
            });

            /*********************** 外部收文单位管理 ******************************/
            var outerUnitTable = table.render({
                elem: '#outerUnitTables',
                url: '/DocumentExchangeOutUnit/query?useFlag=true&time='+ new Date().getTime(),
                page: true,
                cols:[[
                    {field: 'ouTypeName', align: 'center', title: '外部单位类别'},
                    {field: 'ounitFullName', align: 'center', title: '单位全称'},
                    {field: 'ounitShotName', align: 'center', title: '单位简称'},
                    {field: 'ounitName', align: 'center', title: '接收单位名称'},
                    {field: 'deptName', align: 'center', title: '接收部门名称'},
                    {field: 'docType', align: 'center', title: '来文类型',
                        templet: function(d){
                            var str = '';
                            switch (d.docType) {
                                case '1':
                                    str = '上级来文';
                                    break;
                                case '2':
                                    str = '下级来文';
                                    break;
                                case '3':
                                    str = '其他来文';
                                    break;
                                default:
                                    str = '';
                                    break;
                            }
                            return str;
                        }
                    },
                    {field: 'deliveryType', align: 'center', title: '主送/抄送',
                        templet: function (d) {
                            var str = '';
                            if (d.deliveryType == 1) {
                                str = '主送'
                            } else if (d.deliveryType == 2) {
                                str = '抄送'
                            }
                            return str;
                        },
                    },
                    {field: 'ounitDesc', align: 'center', title: '外部单位说明'},
                    {fixed: 'right', title: '操作', align: 'center', toolbar: '#outerUnitBar'}
                ]],
                response: {
                    statusName: 'flag',
                    statusCode: true,
                    dataName: 'obj',
                    countName: 'totleNum'
                }
            });

            //监听-外部收文单位管理-表格-工具条
            table.on('tool(outerUnitTables)', function(obj){
                var tData = obj.data;
                var layEvent = obj.event;

                if(layEvent === '1'){
                    saveOuterUnit(form, 2, outerUnitTable, tData);
                } else if(layEvent === '2'){ //删除
                    layer.confirm('确定删除当前数据?', function(index){
                        obj.del();
                        layer.close(index);
                        $.post('/DocumentExchangeOutUnit/delete', {ouId: tData.ouId}, function(res){
                            if (res.flag) {
                                outerUnitTable.reload({
                                    url: '/DocumentExchangeOutUnit/query?useFlag=true&time='+ new Date().getTime()
                                    ,page: {
                                        curr: 1
                                    }
                                });
                            }
                        });
                    });
                }
            });

            // 新增外部收文单位
            $('.add_btn').on('click', function(){
                saveOuterUnit(form, 1, outerUnitTable)
            });

            // 筛选-外部收文单位管理
            form.on('select(searchSelectOuter)', function(data){
                outerUnitTable.reload({
                    where: {
                        ouType: data.value
                    }
                    ,page: {
                        curr: 1
                    }
                });
            });
        });

        function resetForm(form) {
            $('#newModal').hide();
            $('#newModals').hide();
            $('.exchange_user').empty();
            $('#SendCompany').get(0).setAttribute('deptid', '');
            $('#SendCompany').val('');
            $('#Senduser').get(0).setAttribute('user_id', '');
            $('#Senduser').val('');
            $('#parentDept').get(0).setAttribute('deptid', '');
            $('#parentDept').val('');
            $('#childDepts').get(0).setAttribute('deptid', '');
            $('#childDepts').val('');
            $('#SendCompanys').get(0).setAttribute('deptid', '');
            $('#SendCompanys').val('');
            $('#Sendusers').get(0).setAttribute('user_id', '');
            $('#Sendusers').val('');
            $('#parentDepts').get(0).setAttribute('deptid', '');
            $('#parentDepts').val('');
            $('#childDeptss').get(0).setAttribute('deptid', '');
            $('#childDeptss').val('');
            var checks = $('.documentPriv');
            checks.each(function(){
                this.checked = false;
            });
            form.val("newForm", {
                "fromUnit": '',
                'receiveUnit': '',
                'documentPriv': ''
            });
        }

        // 保存外部单位方法
        function saveOuterUnit(form, optType, tableObj, tData) {

            var title = '添加外部单位';
            var saveUrl = '/DocumentExchangeOutUnit/insert';
            if (optType == 2) {
                title = '修改外部单位';
                saveUrl = '/DocumentExchangeOutUnit/update';
            }

            var layerIndex = layer.open({
                type: 1,
                title: title,
                content: $('#newOuterUnitModal'),
                area: ['600px', '500px'],
                btn: ['确认', '取消'],
                yes: function(){
                    var data = {}
                    if (tData) {
                        data['ouId'] = tData.ouId;
                    }
                    var t = $('#newouterunitform [name]').serializeArray();
                    $.each(t, function() {
                        data[this.name] = this.value.trim();
                    });

                    data['deliveryType'] = $('input[name="deliveryType"]:checked').val();
                    if (!data['ounitFullName']) {
                        layer.msg('请输入单位全称');
                        return false;
                    }
                    if (!data['ounitShotName']) {
                        layer.msg('请输入单位简称');
                        return false;
                    }
                    if (!data['ouType']) {
                        layer.msg('请选择外部单位类别');
                        return false;
                    }
                    if (!data['ounitName']) {
                        layer.msg('请输入接收单位名称');
                        return false;
                    }
                    if (!data['deptName']) {
                        layer.msg('请输入接收单位部门');
                        return false;
                    }
                    if (!data['deliveryType']) {
                        layer.msg('请选择主送/抄送');
                        return false;
                    }
                    if (!data['ounitDesc']) {
                        layer.msg('请输入说明');
                        return false;
                    }

                    $.post(saveUrl, data, function(res){
                        if (res.flag) {
                            layer.close(layerIndex);
                            $('#newOuterUnitModal').hide();
                            tableObj.reload({
                                url: '/DocumentExchangeOutUnit/query?useFlag=true&time='+ new Date().getTime()
                                ,page: {
                                    curr: 1
                                }
                            });
                        }
                    });
                },
                success: function() {

                    if (tData) {
                        var checks = $('.delivery_type');
                        if (tData.deliveryType == 1) {
                            checks[0].checked = true;
                        } else if (tData.deliveryType == 2) {
                            checks[1].checked = true;
                        }
                    }

                    form.val("newouterunitform", {
                        "ouNo": tData ? tData.ouNo : '',
                        'ouType': tData ? tData.ouType : $('.ou_type').children().eq(0).val(),
                        'ounitFullName': tData ? tData.ounitFullName : '',
                        'ounitShotName': tData ? tData.ounitShotName : '',
                        'ounitName': tData ? tData.ounitName : '',
                        'deptName': tData ? tData.deptName : '',
                        'docType': tData ? tData.docType : '1',
                        'ounitDesc': tData ? tData.ounitDesc : ''
                    });
                },
                btn2: function(){
                    $('#newOuterUnitModal').hide();
                    var checks = $('.delivery_type');
                    checks.each(function(){
                        this.checked = false;
                    });
                },
                cancel: function(){
                    $('#newOuterUnitModal').hide();
                    var checks = $('.delivery_type');
                    checks.each(function(){
                        this.checked = false;
                    });
                }
            });
        }

        // 格式化时间 YYYY-MM-DD
        function formatDate(date) {
            var time = '';
            date = new Date(date);
            var month = date.getMonth() +1 < 10 ? '0'+(date.getMonth() +1) : date.getMonth() +1;
            var day = date.getDay() < 10 ? '0'+date.getDay() : date.getDate();
            var hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
            var minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
            var second = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
            time = date.getFullYear() + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
            return time;
        }

    </script>
</body>
</html>